<?php
// only logged in users can add and object
gatekeeper ();

elgg_make_sticky_form ( 'resume' );

// Get user input.
$title = htmlspecialchars ( get_input ( 'title', '', false ), ENT_QUOTES, 'UTF-8' );
$description = get_input ( 'description', '' );
$rate = get_input ( 'rate', 0 );
$group_guid = get_input ( 'group_guid', - 1 );
$skill_guid = get_input ( 'skill_guid', false );
$newskill_flag = true;

if(!$skill_guid){
	$skills = elgg_get_entities ( array (
			'type' => "object",
			'subtype' => "skill",
			'owner_guid' => elgg_get_logged_in_user_guid ()
	) );	
	$skill = null;
	foreach ( $skills as $skillitem ) {
		if (strtolower ( $skillitem->title ) == strtolower ( $title )) {
			$newskill_flag = false;
			$skill = $skillitem;
		}
	}
	
} else {
	$newskill_flag = false;
	$skill = get_entity($skill_guid);
}

// create new skill object
if ($newskill_flag) {
	$skill = new ElggObject ();
	$skill->subtype = "skill";
	$skill->title = $title;
	$skill->description = $description;
	$skill->rate = intval ( $rate );
	$skill->access_id = ACCESS_LOGGED_IN;
	// owner is logged in user
	$skill->owner_guid = elgg_get_logged_in_user_guid ();
} else {
	
	if ($skill) {
		$skill->rate = intval ( $rate );
		if(!$skill_guid){
			$skill->description .= $description;
		} else {
			$skill->description = $description;
		}
		
	}
}

if ($skill->save ()) {
	if ($group_guid != - 1) {
		$group = get_entity ( $group_guid );
		if ($group && elgg_instanceof ( $group, 'group' )) {
			if ($skill->projectnum) {
				$skill->projectnum ++;
			} else {
				$skill->projectnum = 1;
			}
			$skill->save ();
			
			$skill->addRelationship ( $group->register_project, "skillobtained" );
		}
	}
	system_message ( elgg_echo ( 'resume:OK' ) );
}

$action = "create";

// add to river
add_to_river ( 'river/object/resume/create', $action, elgg_get_logged_in_user_guid (), $skill->guid );

// forward user to a main page
forward ( $CONFIG->wwwroot . "resumes/" . elgg_get_logged_in_user_entity ()->username . "?tab=skill" );